package com.security.config.security.authentication.username;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.RequestMatcher;

import java.io.IOException;

/**
 * 用户名密码认证过滤
 * 调用 AuthenticationManager.authenticate() 方法进行认证
 *
 * @author DblSun
 */
public class UsernameAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public UsernameAuthenticationFilter(RequestMatcher requiresAuthenticationRequestMatcher,
                                        AuthenticationManager authenticationManager) {
        super(requiresAuthenticationRequestMatcher, authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UsernameAuthenticationToken usernameAuthenticationToken = new UsernameAuthenticationToken(username, password);
        return this.getAuthenticationManager().authenticate(usernameAuthenticationToken);
    }
}
